package docbookarchivemanager.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Jakub Hrachovec
 */
public class StringHelper {

    /**
     *
     * @param text
     * @param s
     * @return how many times given string contains given string
     */
    public static int getNumberOfCharsInString(String text, String s) {
        int counter = 0;
        if (text.contains(s)) {
            String temp = text;
            while (temp.contains(s)) {
                temp = temp.substring(0, temp.lastIndexOf(s));
                counter++;
            }
        }
        return counter;
    }

    /**
     *
     * @param s
     * @return if given URI is a valid URL.
     */
    public static boolean isValidURL(String s) {
        try {
            new URI(s).toURL();
        } catch (Exception ex) {
            return false;
        }
        return true;
    }

    /**
     *
     * @param pi
     * @param regex
     * @param num
     * @return Value from given string using regex's groups.
     */
    public static String getValue(String pi, String regex, int num) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(pi);
        if (matcher.find()) {
            return matcher.group(num);
        } else {
            return null;
        }
    }

    public static String getPath(String path) {
        Pattern pattern = Pattern.compile("(?<=file:(/+)?)(.*)");
        Matcher matcher = pattern.matcher(path);
        if (matcher.find()) {
            String found = matcher.group(2);
            return found;
        } else {
            return path;
        }
    }

    /**
     * Checks if given String contains given value using regex.
     *
     * @param value
     * @param regex
     * @return if given String contains given value
     */
    public static boolean containsValue(String value, String regex) {
        Pattern pattern = Pattern.compile(regex.toLowerCase());
        Matcher matcher = pattern.matcher(value.toLowerCase());
        return matcher.find();
    }

    /**
     * Checks if given PI value contains a valid stylesheet type.
     *
     * @param value
     * @return if given String contains a valid stylesheet type
     */
    public static boolean containsStylesheet(String value) {
        String typePreRegex = "(\\s+)?type(\\s+)?=(\\s+)?\"(\\s+)?";
        String typePostRegex = "(\\s+)?\"(\\s+)?";

        for (String s : FileManager.CONTENT_TYPES) {
            if (StringHelper.containsValue(value, typePreRegex + s + typePostRegex)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Converts two absolute path into one relative path relative to given path.
     *
     * @param absolutePath
     * @param relativeTo
     * @return relative path relative to given path
     */
    public static String convertToRelativePath(String absolutePath, String relativeTo) {

        StringBuilder relativePath = null;

        absolutePath = absolutePath.replaceAll("\\\\", "/");
        relativeTo = relativeTo.replaceAll("\\\\", "/");

        if (absolutePath.equals(relativeTo) == true) {
            return new File(relativeTo).getName();
        } else {
            String[] absoluteDirectories = absolutePath.split("/");
            String[] relativeDirectories = relativeTo.split("/");

            int length = absoluteDirectories.length < relativeDirectories.length
                    ? absoluteDirectories.length : relativeDirectories.length;

            int lastCommonRoot = -1;
            int index;

            for (index = 0; index < length; index++) {
                if (absoluteDirectories[index].equals(relativeDirectories[index])) {
                    lastCommonRoot = index;
                } else {
                    break;
                }
            }
            if (lastCommonRoot != -1) {
                relativePath = new StringBuilder();
                for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) {
                    if (absoluteDirectories[index].length() > 0) {
                        relativePath.append("..").append("/");
                    }
                }
                for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) {
                    relativePath.append(relativeDirectories[index]).append("/");
                }
                relativePath.append(relativeDirectories[relativeDirectories.length - 1]);
            }
        }
        return relativePath == null ? null : relativePath.toString();
    }

    /**
     * Decodes given string using URLDecoder.
     *
     * @param url
     * @return decoded string
     */
    public static String decodeURL(String url) {
        try {
            return URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex.getMessage());
            return url;
        }
    }

    /**
     * Encodes given string using URLEncoder.
     *
     * @param url
     * @return encoded string
     */
    public static String encodeUrl(String url) {
        try {
            return URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex.getMessage());
            return url;
        }
    }

    public static boolean arrayContains(String[] array, String string) {
        for (String s : array) {
            if (string.equals(s)) {
                return true;
            }
        }
        return false;
    }
}
